package com.gorkr.cronback.pattern.designPattern.singleton;


import cn.hutool.core.date.DateUnit;
import com.gorkr.cronback.pattern.CronPattern;
import com.gorkr.cronback.pattern.designPattern.proxy.ProxyCronPattern;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 单例模式实现工具类
 * 懒汉式双重验证
 */
public class CronPatternUtil {

    private int times = 0;  // 记录该工具类第几次解析， 体现单例模式的优势

    private static volatile CronPatternUtil instance = null;

    private CronPatternUtil(){};

    public static CronPatternUtil getInstance(){
        if(instance == null){
            synchronized (CronPatternUtil.class){
                if(instance == null){
                    instance = new CronPatternUtil();
                }
            }
        }
        return instance;
    }


    /**
     * 列举指定日期范围内所有匹配表达式的日期
     * @param start 起始时间
     * @param end 结束时间
     * @param count 枚举数量
     * @return 日期列表
     */
//    public List<String> matchedDates(CronPattern pattern, long start, long end, int count){
    public List<String> matchedDates(ProxyCronPattern pattern, long start, long end, int count) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        df.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));


        final List<String> result = new ArrayList<>(count);
        long step = DateUnit.MINUTE.getMillis();  // 日期迭代步长
        for (long i = start; i<end; i+=step){
            final GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTimeInMillis(i);
            if(pattern.match(calendar)){
                result.add(df.format(calendar.getTime()));
                if(result.size() >= count){
                    break;
                }
            }
        }

        times ++;
        System.out.println("第--- "+times+" ---次对cron字符串解析");
        return result;

    }

}
